import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, ajax, base, cardCache, toast, getBusinessInfo,getMultiLang,createPageIcon } from 'nc-lightapp-front';
import { onButtonClick, initTemplate } from '../../selfExecute/syncTree/events';
const { NCTable, NCCheckbox: Checkbox, NCDiv } = base;
// import { dataSource,voucher_link } from '../../../public/components/constJSON';
// import { voucherRelatedApp} from '../../../public/components/oftenApi.js';
import ReferLoader from '../../../public/ReferLoader/index.js';
import { accbookRefcode } from '../../../public/ReferLoader/constants.js';
import BusinessUnitVersionDefaultAllTreeRef from '../../../../uapbd/refer/orgv/BusinessUnitVersionDefaultAllTreeRef';
import GLAccPeriodDefaultTreeGridRef from '../../../refer/voucher/GLAccPeriodDefaultTreeGridRef/index';
import './index.less';
import cacheUtils from '../utils/cacheUtils.js';
// let { setDefData, getDefData } = cardCache;
import { pushToLinkVoucher } from '../../../public/common/voucherUtils';
import HeaderArea from '../../../public/components/HeaderArea';
import buSecondRefer from '../../selfExecute/utils/buSecondRefer.js';
import { getTableHeight } from '../../../public/common/method.js';
const emptyCell = <span>&nbsp;</span>
class TransferHistory extends Component {
	constructor(props) {
		super(props);
		this.state = {
			accountingbook: {
				//核算账簿
				refname: '',
				refpk: ''
			},
			period: {
				//会计期间
				refname: '',
				refpk: ''
			},
			tableData: [],
			transferType: '',
			pk_unit: {
				refname: '',
				refpk: ''
			},
			pk_unitState: false,
			checkedDatas: [],
			checkedAll: false,
			checkedArray: [
				// false,
				// false,
				// false,
			],
			combineInfo: {},
			cacheSearchData:{},
			consColumns: [],
			GL123: false,
			liabilityCenter: {
				refname: '',
				refpk: ''
			}, //利润中心
			json: {}
		}
		this.columns = []
		this.groupColumns = []
		this.globalColums = []
		this.onRowClick = this.onRowClick.bind(this);
	}
	// 基础table列
	getInitColumns = (json) => {
		let columns = [
			{
				title: (<div fieldid='m_transferType'>{json['20020HISTORY-000000']}</div>),/* 国际化处理： 类型*/
				dataIndex: 'm_transferType',
				key: 'm_transferType',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_transferType'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_NO'>{json['20020HISTORY-000001']}</div>),/* 国际化处理： 编号*/
				dataIndex: 'm_NO',
				key: 'm_NO',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_NO'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_Note'>{json['20020HISTORY-000002']}</div>),/* 国际化处理： 说明*/
				dataIndex: 'm_Note',
				key: 'm_Note',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_Note'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_operatetime'>{json['20020HISTORY-000003']}</div>),/* 国际化处理： 操作时间*/
				dataIndex: 'm_operatetime',
				key: 'm_operatetime',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_operatetime'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_OperatorName'>{json['20020HISTORY-000004']}</div>),/* 国际化处理： 操作人*/
				dataIndex: 'm_OperatorName',
				key: 'm_OperatorName',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_OperatorName'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_CheckerName'>{json['20020HISTORY-000005']}</div>),/* 国际化处理： 审核人*/
				dataIndex: 'm_CheckerName',
				key: 'm_CheckerName',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_CheckerName'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_RegisterName'>{json['20020HISTORY-000006']}</div>),/* 国际化处理： 记账人*/
				dataIndex: 'm_RegisterName',
				key: 'm_RegisterName',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_RegisterName'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_DebitTotal'>{json['20020HISTORY-000007']}</div>),/* 国际化处理： 账簿本币（借方）*/
				dataIndex: 'm_DebitTotal',
				key: 'm_DebitTotal',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_DebitTotal'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_CreditTotal'>{json['20020HISTORY-000008']}</div>),/* 国际化处理： 账簿本币（贷方）*/
				dataIndex: 'm_CreditTotal',
				key: 'm_CreditTotal',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_CreditTotal'>{text ? text : emptyCell}</div>
			}
		]
		return columns
	}
	// 启用集团本币时渲染，未启用不渲染
	getInitGroupColumns = (json) => {
		let groupColumns = [
			{
				title: (<div fieldid='m_GroupDebitTotal'>{json['20020HISTORY-000009']}</div>),/* 国际化处理： 集团本币（借方）*/
				dataIndex: 'm_GroupDebitTotal',
				key: 'm_GroupDebitTotal',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_GroupDebitTotal'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_GroupCreditTotal'>{json['20020HISTORY-000010']}</div>),/* 国际化处理： 集团本币（贷方）*/
				dataIndex: 'm_GroupCreditTotal',
				key: 'm_GroupCreditTotal',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_GroupCreditTotal'>{text ? text : emptyCell}</div>
			},
		]
		return groupColumns
	}
	// 启用全局本币时渲染，未启用不渲染
	getInitGlobalColums = (json) => {
		let globalColums = [
			{
				title: (<div fieldid='m_GlobalDebitTotal'>{json['20020HISTORY-000011']}</div>),/* 国际化处理： 全局本币（借方）*/
				dataIndex: 'm_GlobalDebitTotal',
				key: 'm_GlobalDebitTotal',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_GlobalDebitTotal'>{text ? text : emptyCell}</div>
			},
			{
				title: (<div fieldid='m_GlobalCreditTotal'>{json['20020HISTORY-000012']}</div>),/* 国际化处理： 全局本币（贷方）*/
				dataIndex: 'm_GlobalCreditTotal',
				key: 'm_GlobalCreditTotal',
				width: '160px',
				render: (text, record, index) => <div fieldid='m_GlobalCreditTotal'>{text ? text : emptyCell}</div>
			},
		]
		return globalColums
	}
	getParm = (parm) => {
		let appUrl = decodeURIComponent(window.location.href).split('?');

		if (appUrl && appUrl[1]) {
			let appPrams = appUrl[1].split('&');
			if (appPrams && appPrams instanceof Array) {
				let parmObj = {};
				appPrams.forEach((item) => {
					let key = item.split('=')[0];
					let value = item.split('=')[1];
					parmObj[key] = value;
				});
				return parmObj[parm];
			}
		}
	};
	handleSearch = () => {
		let { accountingbook, period, tableData, transferType, pk_unit, liabilityCenter } = this.state;
		let url = '/nccloud/gl/voucher/queryTransHis.do';
		let data = {};
		if (accountingbook.refpk && period.refname) {
			data = {
				pk_accountingbook: accountingbook.refpk,
				"year": period.value ? period.value.periodyear.value : period.refname.slice(0, 4),  //会计年
				"period": period.value ? period.value.accperiodmth.value : period.refname.slice(5, 7),
				// year: period.refname.slice(0, 4), //会计年
				// period: period.refname.slice(5, 7),
				transferType: transferType, //"gl_transrate" 汇兑损益 "gl_transfer" 自定义转账,
				pk_unit: pk_unit.refpk,
				pk_liabilitycenter: liabilityCenter.refpk
			};
			let self = this;
			let { checkedArray } = self.state;
			ajax({
				url,
				data,
				success: function(response) {
					let { data, error, success } = response;
					if (success) {
						if (!data) {
							data = [];
						}
						checkedArray = [];
						data.forEach((item, index) => {
							checkedArray.push(false);
							self.setState({
								checkedArray: checkedArray
							});
						});
						self.setState({
							tableData: data
						},()=>{
							if(data.length===0){
								toast({ content: self.state.json['20020HISTORY-000013'], color: 'warning' });/* 国际化处理： 未查询出符合条件的数据*/
							}else if(data.length != 0){
								toast({ content: self.state.json['20020HISTORY-000014'], color: 'success' });/* 国际化处理： 成功查询出数据*/
							}
						});
					} else {
						toast({ content: self.state.json['20020HISTORY-000013'], color: 'warning' });/* 国际化处理： 未查询出符合条件的数据*/
					}
				}
			});
		}
		// else {
		// 	toast({ content: '请完善查询条件', color: 'warning' });
		// 	return;
		// }		
	};
	clearTableData(){
		this.setState({
			tableData: []
		})
	}

	/**
	 * 此页面查询条件不和父级页面联动
	 */
	beforeGoback(){
		// let { cacheSearchData,accountingbook, period, pk_unit,transferType,pk_unitState} = this.state;
		// // let chacheTreeData = this.cacheUtil.getTreeData()
		// // let historyData = {
		// // 	transferType,
		// // 	accountingbook,
		// // 	pk_unit,
		// // 	period,
		// // 	pk_unitState
		// // }
		// cacheSearchData.accountingbook = accountingbook
		// cacheSearchData.period = period
		// cacheSearchData.pk_unit = pk_unit
		// cacheSearchData.pk_unitState = pk_unitState
		// cacheSearchData.transferType = transferType

		// // this.cacheUtil.setTreeData(chacheTreeData)
		// cacheUtils.setSearchData(cacheSearchData)
	}
	handBack = () => {
		// this.beforeGoback()
		let treeData = cacheUtils.getTreeData()
		let tableData = cacheUtils.getTableData()
		cacheUtils.setTreeData(treeData)
		cacheUtils.setTableData(tableData)
		this.props.pushTo('/',{});
	};

	//联查凭证
	goVoucher() {
		let self = this;
		let { checkedDatas, checkedArray, tableData } = self.state;
		this.beforeGoback()
		cacheUtils.setHistoryTableData(tableData)
		checkedDatas = [];
		for (var i = 0; i < checkedArray.length; i++) {
			if (checkedArray[i] === true) {
				checkedDatas.push(tableData[i].m_pk_voucher);
			}
		}
		let backAppCode = self.props.getUrlParam('backAppCode') || self.props.getSearchParam('c')
		let backPageCode = self.props.getUrlParam('backPageCode') || self.props.getSearchParam('p')
		if (checkedDatas.length > 0) {
			let param = {
				pk_voucher: checkedDatas,
				titlename: self.state.json['20020HISTORY-000015'],/* 国际化处理： 凭证联查*/
				backUrl: '/trransferHistory',
				backAppCode: backAppCode,
				backPageCode: backPageCode,
			}
			pushToLinkVoucher(self,param);
			// let key = 'checkedData';
			// setDefData(key, dataSource, checkedDatas);
			// let voucherapp=voucherRelatedApp(voucher_link);
			// self.props.pushTo('/list', {
			// 	appcode: voucherapp.appcode,
			// 	ifshowQuery: true,
			// 	n: self.state.json['20020HISTORY-000015'],/* 国际化处理： 凭证联查*/
			// 	pagekey: 'link',
			// 	status: 'browse',
			// 	backUrl: '/trransferHistory',
			// 	backAppCode: backAppCode,
			// 	backPageCode: backPageCode,
			// });
		}
	}
	//全选
	onAllCheckChange = () => {
		let self = this;
		let checkedArray = [];
		let selIds = [];
		for (var i = 0; i < self.state.checkedArray.length; i++) {
			checkedArray[i] = !self.state.checkedAll;
		}
		self.setState({
			checkedAll: !self.state.checkedAll,
			checkedArray: checkedArray
		},()=>{
			let {checkedArray} = self.state
			if(checkedArray.includes(true)){
				this.props.button.setButtonDisabled(['link2voucher'], false)
			}else{
				this.props.button.setButtonDisabled(['link2voucher'], true)
			}
		});
	};
	//单选
	onCheckboxChange = (text, record, index) => {
		let self = this;
		let allFlag = false;
		let checkedArray = self.state.checkedArray.concat();
		checkedArray[index] = !self.state.checkedArray[index];
		for (var i = 0; i < self.state.checkedArray.length; i++) {
			if (!checkedArray[i]) {
				allFlag = false;
				break;
			} else {
				allFlag = true;
			}
		}
		self.setState({
			checkedAll: allFlag,
			checkedArray: checkedArray
		},()=>{
			let {checkedArray} = self.state
			if(checkedArray.includes(true)){
				this.props.button.setButtonDisabled(['link2voucher'], false)
			}else{
				this.props.button.setButtonDisabled(['link2voucher'], true)
			}
		});
	};
	onRowClick = (record, index, event) => {
		this.onCheckboxChange('', record, index)
	}
	componentWillMount() {
		let callback= (json) =>{
			this.columns = this.getInitColumns(json);
			this.groupColumns = this.getInitGroupColumns(json);
			this.globalColums = this.getInitGlobalColums(json);
			this.setState({
				json:json,
				consColumns: this.columns
			},()=>{		  
				initTemplate.call(this, this.props);
			})
		}
		getMultiLang({moduleId:'20020HISTORY',domainName:'gl',currentLocale:'simpchn',callback});
		this.props.button.setButtonDisabled(['link2voucher'], true)
	}
	componentDidMount() {
		let tempData = cacheUtils.getSearchData()
		let tableData = cacheUtils.getHistoryTableData()
		let transferType = tempData.transferType
		let accountingbook = {
			refname: tempData.accountingbook ? tempData.accountingbook.refname : '',
			refpk: tempData.accountingbook ? tempData.accountingbook.refpk : ''
		}
		let period = {
			refname: tempData.period ? tempData.period.refname : '',
			refpk: tempData.period ? tempData.period.refpk : '',
			value: tempData.period && tempData.period.value ? tempData.period.value : '', //汇兑损益结转,没有传value,没有00期间
		}
		let pk_unit = {
			refname: tempData.pk_unit ? tempData.pk_unit.refname : '',
			refpk: tempData.pk_unit ? tempData.pk_unit.refpk : ''
		}
		let pk_unitState = tempData.pk_unitState

		this.setState({
			transferType,
			accountingbook,
			period,
			pk_unit,
			pk_unitState,
			cacheSearchData: tempData,
			tableData: tableData
		},()=>{
			let {accountingbook,period,tableData} = this.state
			if (accountingbook.refpk && period.refname) {
				this.handleSearch()
				this.queryBookCombineInfo(accountingbook)
			}
		});
	}
	renderColumnsMultiSelect(columns) {
		const { checkedArray } = this.state;
		const { multiSelect, tableData } = this.props;
		let indeterminate_bool = false;
		if (multiSelect && multiSelect.type === 'checkbox') {
			let i = checkedArray.length;
			while (i--) {
				if (checkedArray[i]) {
					indeterminate_bool = true;
					break;
				}
			}
			let defaultColumns = [
				{
					title: (
						<div fieldid='firstcol'>
							<Checkbox
								className="table-checkbox"
								checked={this.state.checkedAll}
								indeterminate={indeterminate_bool && !this.state.checkedAll}
								onChange={this.onAllCheckChange}
							/>
						</div>
					),
					key: 'checkbox',
					attrcode: 'checkbox',
          			dataIndex: 'checkbox',
					width: '60px',
					render: (text, record, index) => {
						return (
							<div fieldid='firstcol'>
								<Checkbox
									className="table-checkbox"
									checked={this.state.checkedArray[index]}
									onChange={this.onCheckboxChange.bind(this, text, record, index)}
								/>
							</div>
						);
					}
				}
			];
			columns = defaultColumns.concat(columns);
		}
		return columns;
	}
	renderCountingBookRef() {
		let { accountingbook } = this.state;
		return (
			<ReferLoader
				showStar={true}
				tag="accbook"
				fieldid='accountingbook'
				isMultiSelectedEnabled={false}
				refcode={accbookRefcode}
				showGroup={false}
				showInCludeChildren={true}
				value={{ refname: accountingbook.refname, refpk: accountingbook.refpk }}
				disabledDataShow={true}
				queryCondition={{
					appcode: this.props.getSearchParam('c'),
					TreeRefActionExt: 'nccloud.web.gl.ref.AccountBookRefSqlBuilder'
				}}
				onChange={(v) => {
					// this.isShowUnit(v);
					this.setState({
						accountingbook: v
					}, () => {
						this.handleSearch();
						this.queryBookCombineInfo(v)
					});
				}}
			/>
		);
	}
	queryBookCombineInfo = (v) => {
		let { consColumns } = this.state
		consColumns = this.columns
		if(!v || !v.refpk){
			return false
		} else {
			ajax({
				url:'/nccloud/gl/voucher/queryBookCombineInfo.do',
				data:{pk_accountingbook:v.refpk},
				success: (res) => {
					let {data,success,error} =res
					if(data){
						if(!data.NC001 && !data.NC002){
							consColumns= this.columns
						} else {
							if(data.NC001 && data.NC002 ){
								let tempColumns = this.columns.concat(this.groupColumns)
								consColumns = tempColumns.concat(this.globalColums)
							} else {
								if(!data.NC001){
									consColumns = this.columns.concat(this.globalColums)
								} else {
									consColumns = this.columns.concat(this.groupColumns)
								}
							}
						}
						this.setState({
							consColumns: consColumns,
							pk_unitState: data.isShowUnit,
							combineInfo: data,
							GL123: data.GL123,
						})
					}
				}
			});
		}
        
		// return consColumns		
		}
	renderTitleSearch = () => {
		let { accountingbook, period, pk_unit, pk_unitState,transferType,combineInfo, GL123 } = this.state;
		let buziInfo = getBusinessInfo();
		let secondReferType = GL123 ? 'liabilityCenter' : 'pk_unit'; //二级账簿:利润中心/业务单元,二选一显示，或均不显示
		return(
			<div className="inputsearch_area">
						<div className="refer-item">
							{this.renderCountingBookRef()}
						</div>
						<div className={transferType==='gl_transfer' && pk_unitState ? 'refer-item' : 'display-none'}>
							{pk_unitState ?
								buSecondRefer(this,{
									referType: secondReferType, 
									pk_accountingbook: accountingbook.refpk, 
									onSetCallBack: () => this.handleSearch(),
								}) : ''
							}
							{/* <BusinessUnitVersionDefaultAllTreeRef
								// isMultiSelectedEnabled={true}
								queryCondition={() => {
									return {
										pk_accountingbook: accountingbook.refpk,
										TreeRefActionExt: 'nccloud.web.gl.ref.GLBUVersionWithBookRefSqlBuilder',
										"isDataPowerEnable": 'Y',"DataPowerOperationCode" : 'fi',
										VersionStartDate: buziInfo.businessDate.split(' ')[0]
									};
								}}
								fieldid='pk_unit'
								value={pk_unit}
								onChange={(v) => {
									pk_unit = v;
									this.setState({
										pk_unit
									},()=>{
										this.handleSearch();
									});
								}}
							/> */}
						</div>

						<div className="refer-item">
							<span className="star">*</span>
							<GLAccPeriodDefaultTreeGridRef
								fieldid='period'
								value={{
									refname: period.refname,
									refpk: period.refpk
								}}
								queryCondition={() => {
									let isShow = transferType==='gl_transfer' ? 'Y' : 'N'
									let condition = {
										pk_accountingbook: accountingbook.refpk,
										showPeriodInit: isShow, //是否显示00
										pk_accperiodscheme: combineInfo.pk_accperiodscheme,
										includeAdj: isShow //是否显示00
									};
									return condition;
								}}
								onChange={(v) => {
									period.refname = v.refname;
									period.refpk = v.refpk;
									period.value = v.values;
									this.setState({
										period
									},()=>{
										this.handleSearch();
									});
								}}
							/>
						</div>
					</div>
		)
	}
	render() {
		let {consColumns} =this.state
		let defaultColumns = consColumns.length === 0 ? this.columns : consColumns
		let columnsldad= this.renderColumnsMultiSelect(defaultColumns);
		let { tableData  } = this.state;
		// let Height = window.innerHeight - 194 + 'px'
		let Height = getTableHeight(80);
		return (
			<div className="nc-single-table history-data-page">
				<HeaderArea 
					title = {this.props.getSearchParam('n')}
					initShowBackBtn = {true}
					backBtnClick = {this.handBack}
					searchContent = {this.renderTitleSearch()}
					btnContent = {this.props.button.createButtonApp({
						area: 'query_header',
						onButtonClick: onButtonClick.bind(this),
						popContainer: document.querySelector('.btn-group')
					})}
				/>
				<div className="table-area">
					<NCDiv fieldid="history" areaCode={NCDiv.config.TableCom}>
						<NCTable 
							columns={columnsldad} 
							data={tableData} 
							bodyStyle={{height: Height}}
							scroll={{x: true, y: Height}}
							onRowClick={this.onRowClick}
						/>
					</NCDiv>
				</div>
			</div>
		);
	}
}

TransferHistory = createPage({
	// initTemplate: initTemplate
	// mutiLangCode: '2052'
})(TransferHistory);
export default TransferHistory;

TransferHistory.defaultProps = {
	prefixCls: 'bee-table',
	multiSelect: {
		type: 'checkbox',
		param: 'key'
	}
};

